//
//  SinaRefreshControl.swift
//  WeiBo01
//
//  Created by mac on 16/1/8.
//  Copyright © 2016年 Han. All rights reserved.
//

import UIKit

/*
1. 创建一个 类,继承自 UIRefreshControl
2. 创建视图,然后我们创建了 SinaRefreshView
3. UIRefreshControl 监听他的frame的一个改变
4. 创建了一个翻转动画
5. 让翻转的动画隐藏,然后显示加载的试图以及动画
6. 加载完成,恢复到之前的状态
*/

class SinaRefreshControl: UIRefreshControl {

    override init() {
        super.init()
        setupUI()
    }

     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }
    
    private func setupUI(){
        
        //隐藏菊花
        tintColor = UIColor.clearColor()
        
        // 修改背景颜色
//        refreshView.backgroundColor = UIColor(white: 240 / 255.0, alpha: 1.0)
//        refreshView.pullView.backgroundColor = UIColor(white: 240 / 255.0, alpha: 1.0)
        
        addSubview(refreshView)
        
        refreshView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
            make.width.equalTo(160)
            make.height.equalTo(60)
        }
        
        //添加监听
        addObserver(self, forKeyPath: "frame", options: [], context: nil)
    }
    
    //标记下拉
    var isTurn:Bool = false
    //标记加载
    var isLoading:Bool = false
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //加载的时候,隐藏pullView,然后转动
        if refreshing && !isLoading{
            refreshView.pullView.hidden = true
            refreshView.loadingAnimation()
            isLoading = true
        }
        
        if object?.frame.origin.y < -50 && !isTurn{
            
            isTurn = true
            refreshView.startTurn()
        }else if object?.frame.origin.y > -50 && isTurn{
            
            isTurn = false
            refreshView.startTurn()
        }
    }
    
    override func endRefreshing() {
        
        super.endRefreshing()
        
        //移除旋转的动画
        refreshView.removeAnimation()
        //让下拉视图显示
        refreshView.pullView.hidden = false
        //回复加载标记的状态
        isLoading = false
    }
    
    //移除监听
    deinit{
        
        removeObserver(self, forKeyPath: "frame")
    }
    
    //MARK:懒加载
    lazy var refreshView: SinaRefreshView = NSBundle.mainBundle().loadNibNamed("SinaRefreshView", owner: nil, options: nil).last as! SinaRefreshView

}















